package chap_05;

import chap_04.Dish;
import org.junit.jupiter.api.Test;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.function.BinaryOperator;

/**
 * 归约
 */
public class Run_04 {
    List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
    List<Dish> menu = Arrays.asList(
            new Dish("pork", false, 800, Dish.Type.MEAT),
            new Dish("beef", false, 700, Dish.Type.MEAT),
            new Dish("chicken", false, 400, Dish.Type.MEAT),
            new Dish("french fries", true, 530, Dish.Type.OTHER),
            new Dish("rice", true, 350, Dish.Type.OTHER),
            new Dish("season fruit", true, 120, Dish.Type.OTHER),
            new Dish("pizza", true, 550, Dish.Type.OTHER),
            new Dish("prawns", false, 300, Dish.Type.FISH),
            new Dish("salmon", false, 450, Dish.Type.FISH) );
    /**
     * 元素求和
     */
    @Test
    public void demo_01() {
        /*Integer sum = numbers.stream()
                // 0 初始值
                .reduce(0, (a, b) -> a + b);*/

        Integer sum = numbers.stream()
                // 0 初始值
                .reduce(0, Integer::sum);
        System.out.println(sum);
    }

    @Test
    public void demo_05() {
        Optional<Integer> sum = numbers.stream()
                // 0 初始值
                .reduce(Integer::sum);
        System.out.println(sum.get());
    }

    @Test
    public void demo_06() {
        //Comparator<Integer> max = Integer::max;
        Optional<Integer> reduce = numbers.stream()
                .reduce(Integer::max);
        reduce.ifPresent(System.out::println);

        numbers.stream()
                .max(Comparator.comparing(Integer::intValue)).ifPresent(System.out::println);
    }

    /**
     * 最大值和最小值
     */
    @Test
    public void demo_02() {
        numbers.stream().reduce(Integer::max).ifPresent(System.out::println);
    }

    @Test
    public void demo_03() {
        numbers.stream()
                .max(Comparator.comparing(i -> i.intValue()))
                .ifPresent(System.out::println);
    }

    @Test
    public void demo_04() {
        Integer reduce = numbers.stream()
                .reduce(-10, Integer::min);
        System.out.println(reduce);
    }

    /**
     * 一数流中有多少个菜
     */
    @Test
    public void demo_07() {
        menu.stream()
                .map(d -> 1)
                .reduce(Integer::sum).ifPresent(System.out::println);

        long count = menu.stream()
                .count();
        System.out.println(count);
    }
}
